package com.uduemc.biso.node.web.api.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.extities.center.HostSetup;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.HConfig;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.HostConfigUtil;
import com.uduemc.biso.node.core.utils.SitePathUtil;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.dto.RequestUpdateAdWoreds;
import com.uduemc.biso.node.web.api.service.HostService;
import com.uduemc.biso.node.web.api.service.HostSetupService;
import com.uduemc.biso.node.web.api.service.WebSiteService;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/host")
@Api(tags = "Host模块")
public class HostController {

	@Autowired
	private HostService hostServiceImpl;

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private HostSetupService hostSetupServiceImpl;

	@Autowired
	private WebSiteService webSiteServiceImpl;

	@Autowired
	private GlobalProperties globalProperties;

	/**
	 * 获取当前主机的配置信息
	 * 
	 * @param siteId
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/get-hconfig-info")
	public JsonResult getHconfigInfo() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		HConfig currentHostConfig = hostServiceImpl.getCurrentHostConfig();
		return JsonResult.ok(currentHostConfig);
	}

	/**
	 * 通过传入的参数 languagetext 对其主机配置信息中的 h_config.language_text
	 * 
	 * @param requestHostBaseInfo
	 * @param errors
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/save-hconfig-languagetext")
	public JsonResult savehconfiglanguagetext(@RequestParam("languagetext") String languagetext)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		HConfig hConfig = hostServiceImpl.getCurrentHostConfig();
		hConfig.setLanguageText(languagetext);
		HConfig updateHostConfig = hostServiceImpl.updateHostConfig(hConfig);
		webSiteServiceImpl.cacheCurrentHostClear();
		return JsonResult.messageSuccess("更新成功！", updateHostConfig);
	}

	/**
	 * 获取网站增值功能所有的配置参数
	 * 
	 * @return
	 */
	@PostMapping("/get-current-host-setup")
	@ApiOperation(value = "增值配置", notes = "获取网站增值功能所有的配置参数")
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中各项数据说明如下\n" + "data.ipgeo IP地址功能 0-关闭 1-启用\n" + "data.backup 备份功能 0-关闭 1-启用\n"
			+ "data.video 视频功能 0-关闭 1-启用\n" + "data.space 最大空间，单位G\n" + "data.page 	页面数\n" + "data.system 	系统数\n" + "data.form 	表单数量\n"
			+ "data.dnum 	绑定域名的数量\n" + "data.articlenum 	文章系统数据条数\n" + "data.productnum 	产品系统数据条数\n" + "data.downitemnum 下载系统数据条数\n"
			+ "data.faqitemnum 	FAQ系统数据条数\n"+ "data.informationitemnum 	信息系统数据条数\n" + "data.imageupload 允许图片上传的大小\n" + "data.fileupload 允许文件上传的大小\n" + "data.videoupload 允许视频上传的大小\n"
			+ "data.audioupload 允许音频上传的大小\n" + "data.flashupload 允许Flash上传的大小\n" + "data.vffileupload 虚拟目录允许上传文件的大小\n" + "data.vfzipupload 虚拟目录允许上传压缩文件的大小\n"
			+ "data.adwordplus 广告词过滤升级增值功能，关键词自定义过滤功能 0-关闭 1-启用\n") })
	public JsonResult getCurrentHostSetup() {
		HostSetup hostSetup = requestHolder.getHostSetup();
		if (hostSetup == null) {
			return JsonResult.ok();
		}
		return JsonResult.ok(hostSetup);
	}

	/**
	 * 获取目前网站空间大小以及可使用的空间大小，单位G，并且带有小数点后两位！
	 * 
	 * @return
	 */
	@PostMapping("/get-current-host-setup-space")
	public JsonResult getCurrentHostSetupSpace() {
		Double space = requestHolder.getHostSetup().getSpace();
		if (space == null || space < 0) {
			space = 99.99;
		}
		long sizeOfDirectory = hostSetupServiceImpl.getUsedSpace();
		double gsize = (double) sizeOfDirectory / (1024 * 1024 * 1024);

		Map<String, Double> hostSpace = new HashMap<>();
		hostSpace.put("space", space);
		hostSpace.put("gsize", gsize);

		return JsonResult.ok(hostSpace);
	}

	/**
	 * 获取目前网站所能创建的网页数量，单位页，整数值
	 * 
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/get-current-host-setup-page")
	public JsonResult getCurrentHostSetupPage() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Map<String, Integer> hostSpace = new HashMap<>();
		int page = hostSetupServiceImpl.getPage();
		int usedPage = hostSetupServiceImpl.getUsedPage();
		hostSpace.put("page", page);
		hostSpace.put("usedPage", usedPage);
		return JsonResult.ok(hostSpace);
	}

	/**
	 * 获取目前网站所能创建的系统数量，单位个，整数值
	 * 
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/get-current-host-setup-system")
	public JsonResult getCurrentHostSetupSystem() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Map<String, Integer> hostSpace = new HashMap<>();
		int system = hostSetupServiceImpl.getSystem();
		int usedSysmte = hostSetupServiceImpl.getUsedSysmte();
		hostSpace.put("system", system);
		hostSpace.put("usedSysmte", usedSysmte);
		return JsonResult.ok(hostSpace);
	}

	/**
	 * 获取目前网站所能创建的表单数量，单位个，整数值
	 * 
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/get-current-host-setup-form")
	public JsonResult getCurrentHostSetupForm() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Map<String, Integer> hostSpace = new HashMap<>();
		int form = hostSetupServiceImpl.getForm();
		int usedForm = hostSetupServiceImpl.getUsedForm();
		hostSpace.put("form", form);
		hostSpace.put("usedForm", usedForm);
		return JsonResult.ok(hostSpace);
	}

	/**
	 * 获取目前网站所能绑定的数量，单位个，整数值
	 * 
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/get-current-host-setup-dnum")
	public JsonResult getCurrentHostSetupDnum() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Map<String, Integer> hostSpace = new HashMap<>();
		int dnum = hostSetupServiceImpl.getDnum();
		int usedDnum = hostSetupServiceImpl.getUsedDnum();
		hostSpace.put("dnum", dnum);
		hostSpace.put("usedDnum", usedDnum);
		return JsonResult.ok(hostSpace);
	}

	/**
	 * 是否存在 favicon 网站图标
	 * 
	 * @return 1 存在 0 不存在
	 */
	@PostMapping("/exsit-favicon")
	public JsonResult exsitFavicon() {
		// 通过 basePath 以及 code 获取 用户的目录
		String userPathByCode = SitePathUtil.getUserPathByCode(globalProperties.getSite().getBasePath(), requestHolder.getHost().getRandomCode());
		String filefullpath = userPathByCode + "/favicon.ico";

		File faviconFile = new File(filefullpath.toString());
		if (faviconFile.isFile()) {
			return JsonResult.ok(1);
		}
		return JsonResult.ok(0);
	}

	/**
	 * 获取备案登录的链接地址
	 * 
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/beian-link")
	@ApiOperation(value = "备案链接", notes = "获取登录到35备案系统链接跳转地址，实现逻辑：如果域名有未备案，且用户存在会员号返回链接地址，前端使用 window.open() 打开；否则返回链接为空")
	public JsonResult beianLink() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		String beianLink = hostServiceImpl.beianLink();
		if (StrUtil.isBlank(beianLink)) {
			return JsonResult.ok();
		}
		return JsonResult.ok(beianLink);
	}

	/**
	 * 获取 h_config 表中字段 site_gray,
	 * disabled_right_click、disabled_copy_paste、disabled_f12
	 * 
	 * 
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/web-site-config")
	@ApiOperation(value = "网站前台设置", notes = "获取对前台生效的一些配置，例如：网页灰度显示、禁止复制功能")
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据列表说明如下\n" + "siteGray 网站灰度设置，默认0 0-关闭 1-开启\n"
			+ "disabledCopy 禁止Copy（包含 禁止右键、禁止复制粘贴、禁止F12），默认0 0-不开启 1-开启\n" + "webRecord 页面底部是否显示备案信息，默认0 0-关闭 1-开启\n") })
	public JsonResult webSiteConfig() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		return hostServiceImpl.webSiteConfig();
	}

	/**
	 * 修改 h_config 表中字段 site_gray
	 * 
	 * @param siteGray
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/update-web-site-config-site-gray")
	@ApiOperation(value = "修改网页灰度显示", notes = "修改网站前台 网页灰度显示 设置")
	@ApiImplicitParams({ @ApiImplicitParam(name = "siteGray", value = "网页灰度显示设置值，0-关闭 1-开启，如果非0、1会给与非法操作提示", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据同 网站前台设置 接口") })
	public JsonResult updateWebSiteConfigSiteGray(@RequestParam("siteGray") Short siteGray)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		siteGray = siteGray == null ? (short) 0 : siteGray.shortValue();
		if (siteGray.shortValue() < (short) 0 || siteGray.shortValue() > (short) 1) {
			return JsonResult.illegal();
		}
		return hostServiceImpl.updateWebSiteConfigSiteGray(siteGray);
	}

	/**
	 * 修改 h_config 表中字段 disabled_right_click、disabled_copy_paste、disabled_f12
	 * 
	 * @param disabledCopy
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/update-web-site-config-disabled-copy")
	@ApiOperation(value = "修改网页禁止复制", notes = "修改网站前台 网页禁止复制 设置")
	@ApiImplicitParams({ @ApiImplicitParam(name = "disabledCopy", value = "网页禁止复制设置值，0-不开启 1-开启，如果非0、1会给与非法操作提示", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据同 网站前台设置 接口") })
	public JsonResult updateWebSiteConfigDisabledCopy(@RequestParam("disabledCopy") Short disabledCopy)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		disabledCopy = disabledCopy == null ? (short) 0 : disabledCopy.shortValue();
		if (disabledCopy.shortValue() < (short) 0 || disabledCopy.shortValue() > (short) 1) {
			return JsonResult.illegal();
		}
		return hostServiceImpl.updateWebSiteConfigDisabledCopy(disabledCopy);
	}

	@PostMapping("/update-web-site-config-web-record")
	@ApiOperation(value = "修改备案号是否显示", notes = "修改网站前台 网站底部备案号是否显示 设置")
	@ApiImplicitParams({ @ApiImplicitParam(name = "webRecord", value = "网站底部备案号是否显示， 0-不显示 1-显示，如果非0、1会给与非法操作提示", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据同 网站前台设置 接口") })
	public JsonResult updateWebSiteConfigWebRecord(@RequestParam("webRecord") Short webRecord)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		webRecord = webRecord == null ? (short) 0 : webRecord.shortValue();
		if (webRecord.shortValue() < (short) 0 || webRecord.shortValue() > (short) 1) {
			return JsonResult.illegal();
		}
		return hostServiceImpl.updateWebSiteConfigWebRecord(webRecord);
	}

	@PostMapping("/sysdomain-access-token")
	@ApiOperation(value = "获取系统域名访问的密码", notes = "无参数，直接获取密码")
	public JsonResult sysdomainAccessToken() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Host host = requestHolder.getHost();
		HConfig hConfig = hostServiceImpl.getCurrentHostConfig();
		String sysdomainAccessPwd = HostConfigUtil.sysdomainAccessPwd(hConfig, host);
		return JsonResult.ok(sysdomainAccessPwd);
	}

	@PostMapping("/update-sysdomain-access-token")
	@ApiOperation(value = "修改系统域名访问的密码", notes = "需参数传递修改后的密码")
	@ApiImplicitParams({ @ApiImplicitParam(name = "token", value = "修改后的密码", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "data 返回修改后的密码！") })
	public JsonResult updateSysdomainAccessToken(@RequestParam("token") String token)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (StrUtil.isBlank(token)) {
			return JsonResult.illegal();
		}
		if (StrUtil.length(token) < 3) {
			return JsonResult.messageError("密码长度至少3位！");
		}

		return hostServiceImpl.updateSysdomainAccessToken(token);
	}

	/**
	 * 获取当前站点的语言版本展示样式
	 */
	@ApiOperation(value = "语言版本展示样式", notes = "获取当前站点的语言版本展示样式")
	@ApiResponses({ @ApiResponse(code = 200, message = "data 数据说明 1-语言文字 2-国家旗帜") })
	@PostMapping("/get-language-style")
	public JsonResult getLanguageStyle() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		HConfig hConfig = hostServiceImpl.getCurrentHostConfig();
		if (hConfig == null) {
			return JsonResult.assistance();
		}
		Integer languageStyle = hConfig.getLanguageStyle();
		if (languageStyle == null) {
			languageStyle = 1;
		}
		return JsonResult.ok(languageStyle);
	}

	/**
	 * 修改当前站点的语言版本展示样式
	 */
	@ApiOperation(value = "修改语言版本展示样式", notes = "获取当前站点的语言版本展示样式，然后进行修改")
	@ApiImplicitParams({ @ApiImplicitParam(name = "languageStyle", value = "修改语言版本展示样式传入的参数，1-语言文字 2-国家旗帜 3-下拉显示", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "data 数据说明 1-语言文字 2-国家旗帜 3-下拉显示") })
	@PostMapping("/update-language-style")
	public JsonResult updateLanguageStyle(@RequestParam("languageStyle") int languageStyle)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (languageStyle > 3 || languageStyle < 1) {
			return JsonResult.illegal();
		}

		HConfig hConfig = hostServiceImpl.getCurrentHostConfig();
		if (hConfig == null) {
			return JsonResult.assistance();
		}
		if (hConfig.getLanguageStyle() != null && hConfig.getLanguageStyle().intValue() == languageStyle) {
			return JsonResult.ok(hConfig.getLanguageStyle());
		}

		return hostServiceImpl.updateLanguageStyle(languageStyle);
	}

	/**
	 * 获取 h_config 表中字段 form_email, email_inbox
	 *
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/email-remind-config-list")
	@ApiOperation(value = "邮件提醒设置列表", notes = "邮件提醒设置列表")
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据列表说明如下\n" + "type 提醒类型  例 formEmail\n" + "status 邮件提醒开关，默认0 0-不发送 1-发送\n"
			+ "emailAddress 提醒邮箱设置 zhansan@35.cn,lisi@35.cn 多个邮箱以 , 为分隔符\n") })
	public JsonResult emailRemindConfigList() throws IOException {
		return hostServiceImpl.emailRemindConfigList();
	}

	@PostMapping("/update-email-remind-status")
	@ApiOperation(value = "修改邮件提醒开关", notes = "修改是否开启邮件提醒的设置")
	@ApiImplicitParams({ @ApiImplicitParam(name = "type", value = "邮件提醒类型， 目前有formEmail, 非指定值会给与非法操作提示", required = true),
			@ApiImplicitParam(name = "status", value = "邮件提醒开关， 0-不发送 1-发送，如果非0、1会给与非法操作提示", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据同 邮件提醒设置列表 接口") })
	public JsonResult updateEmailRemindConfigFormEmail(@RequestParam("type") String type, @RequestParam("status") Integer status) throws IOException {
		if (StringUtils.isBlank(type) || !type.equals("formEmail")) {
			return JsonResult.illegal();
		}
		status = status == null ? 0 : status;
		if (status < 0 || status > 1) {
			return JsonResult.illegal();
		}
		return hostServiceImpl.updateEmailRemindStatus(type, status);
	}

	@PostMapping("/update-email-remind-address")
	@ApiOperation(value = "修改邮件提醒邮箱", notes = "修改开启邮件提醒时接收提醒邮件的邮箱")
	@ApiImplicitParams({ @ApiImplicitParam(name = "type", value = "邮件提醒类型， 目前有formEmail, 非指定值会给与非法操作提示", required = true),
			@ApiImplicitParam(name = "emailAddress", value = "接收提醒邮件的邮箱 zhansan@35.cn,lisi@35.cn 多个邮箱以 , 为分隔符", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据同 邮件提醒设置列表 接口") })
	public JsonResult updateEmailRemindConfigFormEmail(@RequestParam("type") String type, @RequestParam("emailAddress") String emailAddress)
			throws IOException {
		if (StringUtils.isBlank(type) || !type.equals("formEmail")) {
			return JsonResult.illegal();
		}
		emailAddress = emailAddress == null ? "" : emailAddress;
		return hostServiceImpl.updateEmailRemindAddress(type, emailAddress);
	}

	@PostMapping("/ad-words")
	@ApiOperation(value = "非法词过滤配置", notes = "获取非法词过滤相关配置")
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据说明。adFilter:是否开启 0-关闭 1-开启、adWords:用户配置的非法词、default:系统默认非法词") })
	public JsonResult adWoreds() throws IOException {
		return hostServiceImpl.adWoreds();
	}

	@PostMapping("/update-ad-words")
	@ApiOperation(value = "修改非法词过滤", notes = "修改非法词过滤相关配置")
	@ApiResponses({ @ApiResponse(code = 200, message = "data 中数据说明。adFilter:是否开启 0-关闭 1-开启、adWords:用户配置的非法词、default:系统默认非法词") })
	public JsonResult updateAdWoreds(@Valid @RequestBody RequestUpdateAdWoreds requestUpdateAdWoreds, BindingResult errors) throws IOException {
		if (errors.hasErrors()) {
			for (FieldError fieldError : errors.getFieldErrors()) {
				String defaultMessage = fieldError.getDefaultMessage();
				return JsonResult.messageError(defaultMessage);
			}
		}
		return hostServiceImpl.updateAdWoreds(requestUpdateAdWoreds);
	}

}
